package com.tianyuan.lims.dms;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.druid.DruidPlugin;
import com.tianyuan.lims.common.config.JfinalConfig;
import com.tianyuan.lims.dms.entity.*;
import com.tianyuan.lims.erp.admin.entity.*;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class _MappingKit {


	private static List<String> getTableNames(String url, String username, String password) {
		List<String> tableNames = new ArrayList<>();
		try (Connection connection = DriverManager.getConnection(url, username, password)) {
			DatabaseMetaData metaData = connection.getMetaData();
			ResultSet resultSet = metaData.getTables(null, null, null, new String[]{"TABLE"});
			while (resultSet.next()) {
				tableNames.add(resultSet.getString("TABLE_NAME"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tableNames;
	}


	private static List<String> getTableNames(DruidPlugin druidPlugin) {
		List<String> tableNames = new ArrayList<>();
		try (Connection connection = druidPlugin.getDataSource().getConnection()) {
			DatabaseMetaData metaData = connection.getMetaData();
			ResultSet resultSet = metaData.getTables(null, null, null, new String[]{"TABLE"});
			while (resultSet.next()) {
				tableNames.add(resultSet.getString("TABLE_NAME"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tableNames;
	}

	private static String convertTableNameToEntityClassName(String tableName) {
		// 去掉前缀
		if(StringUtils.isNotEmpty(tableName) && tableName.contains("lims_")) {
			tableName = tableName.replaceFirst("^(lims_)", "");
			StringBuilder className = new StringBuilder();
			String[] parts = tableName.split("_");
			for (String part : parts) {
				className.append(Character.toUpperCase(part.charAt(0))).append(part.substring(1));
			}
			return className.toString();
		}
		return "";
	}


	public static void mapping(ActiveRecordPlugin arp) {




		arp.addMapping("crm_admin_dept", "dept_id", AdminDept.class);
		arp.addMapping("crm_admin_examine", "examine_id", AdminExamine.class);
		arp.addMapping("crm_admin_config", "setting_id", AdminConfig.class);
		arp.addMapping("crm_admin_examine_record", "record_id", AdminExamineRecord.class);
		arp.addMapping("crm_admin_examine_step", "step_id", AdminExamineStep.class);
		arp.addMapping("crm_admin_examine_log", "log_id", AdminExamineLog.class);
		arp.addMapping("crm_admin_field", "field_id", AdminField.class);
		arp.addMapping("crm_admin_field_sort", "field_id", AdminFieldSort.class);
		arp.addMapping("crm_admin_field_style", "id", AdminFieldStyle.class);
		arp.addMapping("crm_admin_fieldv", "id", AdminFieldv.class);
		arp.addMapping("crm_admin_file", "file_id", AdminFile.class);
		arp.addMapping("crm_admin_menu", "menu_id", AdminMenu.class);
		arp.addMapping("crm_admin_message", "message_id", AdminMessage.class);
		arp.addMapping("crm_admin_record", "record_id", AdminRecord.class);
		arp.addMapping("crm_admin_role", "role_id", AdminRole.class);
		arp.addMapping("crm_admin_role_menu", "id", AdminRoleMenu.class);
		arp.addMapping("crm_admin_scene", "scene_id", AdminScene.class);
		arp.addMapping("crm_admin_scene_default", "default_id", AdminSceneDefault.class);
		arp.addMapping("crm_admin_user", "user_id", AdminUser.class);
		arp.addMapping("crm_admin_user_role", "id", AdminUserRole.class);



//		arp.addMapping("crm_admin_dept", "dept_id", AdminDept.class);
//		arp.addMapping("crm_admin_examine", "examine_id", AdminExamine.class);
//		arp.addMapping("crm_admin_config", "setting_id", AdminConfig.class);
//		arp.addMapping("crm_admin_examine_record", "record_id", AdminExamineRecord.class);
//		arp.addMapping("crm_admin_examine_step", "step_id", AdminExamineStep.class);
//		arp.addMapping("crm_admin_examine_log", "log_id", AdminExamineLog.class);
//		arp.addMapping("crm_admin_field", "field_id", AdminField.class);
//		arp.addMapping("crm_admin_field_sort", "field_id", AdminFieldSort.class);
//		arp.addMapping("crm_admin_field_style", "id", AdminFieldStyle.class);
//		arp.addMapping("crm_admin_fieldv", "id", AdminFieldv.class);
//		arp.addMapping("crm_admin_file", "file_id", AdminFile.class);
//		arp.addMapping("crm_admin_menu", "menu_id", AdminMenu.class);
//		arp.addMapping("crm_admin_message", "message_id", AdminMessage.class);
//		arp.addMapping("crm_admin_record", "record_id", AdminRecord.class);
//		arp.addMapping("crm_admin_role", "role_id", AdminRole.class);
//		arp.addMapping("crm_admin_role_menu", "id", AdminRoleMenu.class);
//		arp.addMapping("crm_admin_scene", "scene_id", AdminScene.class);
//		arp.addMapping("crm_admin_scene_default", "default_id", AdminSceneDefault.class);
//		arp.addMapping("crm_admin_user", "user_id", AdminUser.class);
//		arp.addMapping("crm_admin_user_role", "id", AdminUserRole.class);
//		arp.addMapping("72crm_crm_business", "business_id", CrmBusiness.class);
//		arp.addMapping("72crm_crm_achievement", "achievement_id", CrmAchievement.class);
//		arp.addMapping("72crm_crm_action_record", "id", CrmActionRecord.class);
//		arp.addMapping("72crm_crm_business_product", "r_id", CrmBusinessProduct.class);
//		arp.addMapping("72crm_crm_business_status", "status_id", CrmBusinessStatus.class);
//		arp.addMapping("72crm_crm_business_type", "type_id", CrmBusinessType.class);
//		arp.addMapping("72crm_crm_contacts", "contacts_id", CrmContacts.class);
//		arp.addMapping("72crm_crm_contacts_business", "id", CrmContactsBusiness.class);
//		arp.addMapping("72crm_crm_contract", "contract_id", CrmContract.class);
//		arp.addMapping("72crm_crm_contract_product", "r_id", CrmContractProduct.class);
//		arp.addMapping("72crm_crm_customer", "customer_id", CrmCustomer.class);
//		arp.addMapping("72crm_crm_customer_setting", "setting_id", CrmCustomerSetting.class);
//		arp.addMapping("72crm_crm_customer_settinguser", "id", CrmCustomerSettingUser.class);
//		arp.addMapping("72crm_crm_leads", "leads_id", CrmLeads.class);
//		arp.addMapping("72crm_crm_owner_record", "record_id", CrmOwnerRecord.class);
//		arp.addMapping("72crm_crm_product", "product_id", CrmProduct.class);
//		arp.addMapping("72crm_crm_product_category", "category_id", CrmProductCategory.class);
//		arp.addMapping("72crm_crm_receivables", "receivables_id", CrmReceivables.class);
//		arp.addMapping("72crm_crm_receivables_plan", "plan_id", CrmReceivablesPlan.class);
//		arp.addMapping("72crm_oa_action_record", "log_id", OaActionRecord.class);
//		arp.addMapping("72crm_oa_announcement", "announcement_id", OaAnnouncement.class);
//		arp.addMapping("72crm_oa_event", "event_id", OaEvent.class);
//		arp.addMapping("72crm_oa_event_relation", "eventrelation_id", OaEventRelation.class);
//		arp.addMapping("72crm_oa_examine_category", "category_id", OaExamineCategory.class);
//		arp.addMapping("72crm_oa_examine_relation", "r_id", OaExamineRelation.class);
//		arp.addMapping("72crm_oa_examine_travel", "travel_id", OaExamineTravel.class);
//		arp.addMapping("72crm_oa_examine", "examine_id", OaExamine.class);
//		arp.addMapping("72crm_oa_examine_log", "log_id", OaExamineLog.class);
//		arp.addMapping("72crm_oa_examine_record", "record_id", OaExamineRecord.class);
//		arp.addMapping("72crm_oa_examine_step", "step_id", OaExamineStep.class);
//		arp.addMapping("72crm_oa_log", "log_id", OaLog.class);
//        arp.addMapping("72crm_oa_log_relation", "r_id", OaLogRelation.class);
//        arp.addMapping("72crm_task", "task_id", Task.class);
//        arp.addMapping("72crm_task_comment", "comment_id", TaskComment.class);
//        arp.addMapping("72crm_task_relation", "r_id", TaskRelation.class);
//        arp.addMapping("72crm_work", "work_id", Work.class);
//        arp.addMapping("72crm_work_task_class", "class_id", WorkTaskClass.class);
//        arp.addMapping("72crm_work_task_label", "label_id", WorkTaskLabel.class);
//        arp.addMapping("72crm_work_task_log", "log_id", WorkTaskLog.class);
//        arp.addMapping("72crm_work_user", "id", WorkUser.class);
//        arp.addMapping("72crm_crm_business_change", "change_id", CrmBusinessChange.class);
//        arp.addMapping("lims_area", "id", LimsArea.class);
//        arp.addMapping("lims_orgtype", "id", LimsOrgtype.class);
//        arp.addMapping("lims_staticsdata", "id", LimsStaticsdata.class);
//        arp.addMapping("lims_devicetype", "id", LimsDevicetype.class);
//        arp.addMapping("lims_expert", "id", LimsExpert.class);
//        arp.addMapping("lims_organization", "id", LimsOrganization.class);
//        arp.addMapping("lims_orgsite", "id", LimsOrgsite.class);
//        arp.addMapping("lims_orgstatics", "id", LimsOrgstatics.class);
//        arp.addMapping("lims_orgtype", "id", LimsOrgtype.class);
//        arp.addMapping("lims_staticsdata", "id", LimsStaticsdata.class);
//        arp.addMapping("lims_device", "id", LimsDevice.class);
//		arp.addMapping("lims_datasource", "id", LimsDatasource.class);
//		arp.addMapping("lims_devicestatics", "id", LimsDevicestatics.class);
//		arp.addMapping("lims_org_score", "id", LimsOrgScore.class);
//
//		arp.addMapping("lims_sitetype", "id", LimsSitetype.class);
//		arp.addMapping("lims_sitetype_conf", "id", LimsSitetypeConf.class);
//
//
//		arp.addMapping("lims_stat_topic", "id", LimsStatTopic.class);
//		arp.addMapping("lims_stat_topic_site", "id", LimsStatTopicSite.class);
//		arp.addMapping("lims_stat_topic_site_item", "id", LimsStatTopicSiteItem.class);
//
//		arp.addMapping("lims_up_ywfp", "id", LimsUpYwfp.class);
//		arp.addMapping("lims_up_ywfp_status", "id", LimsUpYwfpStatus.class);
//
//		arp.addMapping("lims_up_duanmian", "id", LimsUpDuanmian.class);
//		arp.addMapping("lims_up_duanmian_jiancejieguo", "id", LimsUpDuanmianJiancejieguo.class);
//
//		arp.addMapping("lims_up_ywfp_dianwei", "id", LimsUpYwfpDianwei.class);
//
//		arp.addMapping("lims_orgcert", "id", LimsOrgcert.class);
//
//		arp.addMapping("lims_hn_air_pdata_day", "id", LimsHnAirPdataDay.class);
//		arp.addMapping("lims_hn_air_pdata_hour", "id", LimsHnAirPdataHour.class);
//		arp.addMapping("lims_hn_air_pdata_site_day", "id", LimsHnAirPdataSiteDay.class);
//		arp.addMapping("lims_hn_air_pdata_site_hour", "id", LimsHnAirPdataSiteHour.class);
//		arp.addMapping("lims_hn_water_pdata_source", "id", LimsHnWaterPdataSource.class);
//		arp.addMapping("lims_hn_water_pdata_duanmian", "id", LimsHnWaterPdataDm.class);
//		arp.addMapping("lims_hn_water_pdata_duanmian_jiancejieguo", "id", LimsHnWaterPdataJiancejieguo.class);
//		arp.addMapping("lims_hn_noise_transport_data", "id", LimsHnNoiseTransport.class);
//		arp.addMapping("lims_hn_noise_functional_zone_data", "id", LimsHnNoiseFunctionalZone.class);
//		arp.addMapping("lims_hn_noise_area_data", "id", LimsHnNoiseArea.class);
//		arp.addMapping("lims_hn_noise_area_source_data", "id", LimsHnNoiseAreaSource.class);



		arp.addMapping("zbt_product_wty", "id", ZbtProductWty.class);

		// TODO remove bellow code
//		DruidPlugin druidPlugin = JfinalConfig.createDruidPlugin();
//		druidPlugin.start();
		List<String> tableNames = getTableNames(JfinalConfig.prop.get("mysql.jdbcUrl"),
				JfinalConfig.prop.get("mysql.user"), JfinalConfig.prop.get("mysql.password").trim());
		for (String tableName : tableNames) {
			String entityClassName = convertTableNameToEntityClassName(tableName);
			if(StringUtils.isNotEmpty(entityClassName)){
				try {
					Class<?> entityClass = Class.forName("com.tianyuan.lims.dms.entity.Lims" + entityClassName);
					arp.addMapping(tableName, "id", (Class<? extends Model<?>>) entityClass);
					System.out.println("Entity class addMapping for table: " + tableName + "[Lims" + entityClassName + "]");
					int a = 0;
				} catch (ClassNotFoundException e) {
					System.err.println("Entity class not found for table: " + tableName + "[Lims" + entityClassName + "]");
					//e.printStackTrace();
				}
			}
		}



    }
}

